layui.use(['form', 'jquery', 'jquery_cookie'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        $ = layui.jquery_cookie($);

    /**
     * 用户登录
     */
    form.on("submit(login)", function (res) {
        // 获取表单元素的值
        var fieldData = res.field;

        // 判断参数是否为空
        if (fieldData.username === "undefined" || fieldData.username.trim() === "") {
            layer.msg("用户名不能为空！");
            return false;
        }

        if (fieldData.password === "undefined" || fieldData.password === "") {
            layer.msg("密码不能为空！");
            return false;
        }

        $.ajax({
            type: "post",
            url: ctx + "/user/login",
            data: {
                userName: fieldData.username,
                passWord: fieldData.password
            },
            dataType: "json",
            success: function (data) {
                if (data.code === 200) {
                    layer.msg("登录成功！", function () {
                        // 将用户信息存到cookie中
                        var result = data.result;
                        $.cookie("userIdStr", result.userIdStr);
                        $.cookie("userName", result.userName);
                        $.cookie("trueName", result.trueName);

                        //是否勾选记住密码，7天免登录
                        if ($(".rememberMe").is(":checked")) {
                            console.log("勾选了记住密码");
                            $.cookie("userIdStr", result.userIdStr, {
                                expires: 7
                            });
                            $.cookie("userName", result.userName, {
                                expires: 7
                            });
                            $.cookie("trueName", result.trueName, {
                                expires: 7
                            });
                        }
                        // 登录成功后，跳转到首页
                        window.location.href = ctx + "/main";
                    });
                } else {
                    layer.msg(data.msg);
                }
            }
        });
        //阻止表单跳转
        return false;
    });

});